<template>
  <div class="menu-management-container">
    <!-- 筛选区和设置图标同一行 -->
    <div class="filter-bar">
      <div class="filter-container">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          size="small"
        >
        </el-date-picker>

        <el-input
          v-model="searchQuery"
          placeholder="搜索菜单名称"
          prefix-icon="el-icon-search"
          clearable
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
          style="width: 250px; margin-left: 10px;"
          size="small"
        >
        </el-input>

        <el-button type="primary" style="margin-left: 10px;" size="small" @click="handleSearch">查询</el-button>
        <el-button type="default" size="small" @click="resetSearch">重置</el-button>
        <el-button type="primary" size="small" @click="handleAdd">添加</el-button>
      </div>
      <div class="filter-setting-icon">
        <el-popover
          placement="bottom-end"
          width="220"
          trigger="click"
          v-model="showColumnSetting"
        >
          <div v-for="col in columns" :key="col.key">
            <el-checkbox v-model="col.visible">{{ col.label }}</el-checkbox>
          </div>
          <div style="text-align: right;">
            <el-button type="text" size="mini" @click="resetColumns">重置</el-button>
          </div>
          <i
            class="el-icon-setting"
            slot="reference"
            style="cursor: pointer; font-size: 20px; margin-left: 10px;"
          ></i>
        </el-popover>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-wrapper">
      <el-table
        :data="tableData"
        style="width: 100%;"
        border
        v-loading="loading"
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
      <el-table-column v-if="getColumnVisible('index')"
        type="index"
        label="序号"
        width="80"
        align="center">
      </el-table-column>
      <el-table-column v-if="getColumnVisible('menuName')"
        prop="menuName"
        label="菜单名称"
        min-width="150">
        <template slot-scope="scope">
          <span class="custom-tree-node">
            <i :class="[scope.row.children && scope.row.children.length > 0 ? 'el-icon-folder' : 'el-icon-document']" style="margin-right: 8px;"></i>
            <span>{{ scope.row.menuName }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column v-if="getColumnVisible('route')"
        prop="route"
        label="路由"
        min-width="150">
      </el-table-column>
      <el-table-column v-if="getColumnVisible('parentMenu')"
        prop="parentMenu"
        label="父菜单"
        min-width="150">
      </el-table-column>
      <el-table-column v-if="getColumnVisible('listorder')"
        prop="listorder"
        label="显示顺序"
        width="100"
        align="center">
      </el-table-column>
      <el-table-column v-if="getColumnVisible('createTime')"
        prop="createTime"
        label="创建时间"
        width="180">
      </el-table-column>
      <el-table-column v-if="getColumnVisible('updateTime')"
        prop="updateTime"
        label="更新时间"
        width="180">
      </el-table-column>
      <el-table-column v-if="getColumnVisible('operate')"
        label="操作"
        width="150"
        align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" style="color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      </el-table>
    </div>

    <!-- 总条数显示 -->
    <!-- <div class="pagination-info-total">
      <span>共 {{ totalData }} 条数据</span>
    </div> -->

    <!-- 分页组件 -->
    <div class="pagination-container">
      <PageCom :total="totalData" :pageSize="pageSize" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" :currentPage="currentPage"></PageCom>
    </div>

    <!-- 添加/编辑菜单弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      @close="resetDialogForm"
    >
      <el-form :model="dialogForm" :rules="dialogFormRules" ref="dialogForm" label-width="80px">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="dialogForm.name"></el-input>
        </el-form-item>
        <el-form-item label="路由" prop="url">
          <el-input v-model="dialogForm.url"></el-input>
        </el-form-item>
        <el-form-item label="父菜单" prop="parentId">
          <el-select v-model="dialogForm.parentId" placeholder="请选择父菜单" style="width: 100%">
            <el-option label="无" value="0"></el-option>
            <el-option
              v-for="item in menuOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="显示顺序" prop="listorder">
          <el-input-number v-model="dialogForm.listorder" :min="0" label="显示顺序"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDialogForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getMenuData, menuAdd, menuEdit, menuDelete } from '@/api/contract'
import PageCom from '@/components/PageCom.vue';

export default {
  name: 'MenuManagementView',
  components: {
    PageCom,
  },
  data() {
    return {
      dateRange: null,
      searchQuery: '',
      loading: false,
      // 分页相关数据
      currentPage: 1,
      pageSize: 10,
      tableData: [],
      totalData: 0,
      dialogVisible: false,
      dialogTitle: '添加菜单',
      dialogForm: {
        id: null,
        name: '',
        url: '',
        parentId: '0',
        listorder: 0
      },
      dialogFormRules: {
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入路由', trigger: 'blur' }
        ],
        listorder: [
           { required: true, message: '请输入显示顺序', trigger: 'change' },
           { type: 'number', message: '显示顺序必须为数字' }
        ]
      },
      menuOptions: [],
      allMenuData: [],
      // 字段显示控制配置
      columns: [
        { key: 'index', label: '序号', visible: true },
        { key: 'menuName', label: '菜单名称', visible: true },
        { key: 'route', label: '路由', visible: true },
        { key: 'parentMenu', label: '父菜单', visible: true },
        { key: 'listorder', label: '显示顺序', visible: true },
        { key: 'createTime', label: '创建时间', visible: true },
        { key: 'updateTime', label: '更新时间', visible: true },
        { key: 'operate', label: '操作', visible: true }
      ],
      showColumnSetting: false,
    }
  },
  created() {
    this.fetchMenuList()
  },
  methods: {
    // 获取菜单列表
    async fetchMenuList() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          time: this.dateRange,
          keyword: this.searchQuery
        }
        const response = await getMenuData(params)
        // console.log('菜单列表响应:', response)
        if (response.data.code === 200) {
          const menuData = response.data.data
          if(response.data.data.total === 0){
            this.$message.warning('暂无数据');
          }
          // 保存所有菜单数据
          this.allMenuData = menuData.data
          // 构建树形结构
          this.tableData = this.buildMenuTree(menuData.data)
          this.totalData = menuData.total
          // 更新父菜单选项
          this.updateMenuOptions(menuData.data)
        } else {
          this.$message.error(response.data.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取菜单列表失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    // 构建菜单树
    buildMenuTree(menuList) {
      const menuMap = {}
      const result = []

      // 先将所有菜单项转换为需要的格式
      menuList.forEach(item => {
        menuMap[item.id] = {
          id: item.id,
          menuName: item.name,
          route: item.url,
          parentMenu: item.parentId === 0 ? '根菜单' : this.getParentMenuName(item.parentId),
          createTime: item.create_time,
          updateTime: item.update_time,
          children: [],
          listorder: item.listorder
        }
      })

      // 构建树形结构
      menuList.forEach(item => {
        const menu = menuMap[item.id]
        if (item.parentId === 0) {
          result.push(menu)
        } else {
          const parent = menuMap[item.parentId]
          if (parent) {
            parent.children.push(menu)
          }
        }
      })

      return result
    },
    // 更新父菜单选项
    updateMenuOptions(menuList) {
      this.menuOptions = menuList.map(item => ({
        value: item.id.toString(),
        label: item.name
      }))
    },
    // 获取父菜单名称
    getParentMenuName(parentId) {
      const parentMenu = this.allMenuData.find(item => item.id === parentId)
      return parentMenu ? parentMenu.name : ''
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchMenuList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchMenuList()
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchMenuList()
    },
    resetSearch() {
      this.dateRange = null
      this.searchQuery = ''
      this.currentPage = 1
      this.fetchMenuList()
    },
    handleAdd() {
      this.dialogTitle = '添加菜单'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.dialogForm.resetFields()
        this.dialogForm.parentId = '0' // 默认选择无父菜单
      })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑菜单'
      this.dialogVisible = true
      this.$nextTick(() => {
        // 填充表单数据
        this.dialogForm = {
          id: row.id,
          name: row.menuName,
          url: row.route,
          parentId: row.parentMenu === '根菜单' ? '0' : this.getParentIdByName(row.parentMenu),
          listorder: row.listorder
        }
      })
    },
    // 根据菜单名称获取ID
    getParentIdByName(menuName) {
      const menu = this.allMenuData.find(item => item.name === menuName)
      return menu ? menu.id.toString() : '0'
    },
    handleDelete(row) {
      // 检查是否有子菜单
      if (row.children && row.children.length > 0) {
        this.$message.info('请先删除下边的子菜单');
        return;
      }
      
      this.$confirm(`确定删除菜单 "${row.menuName}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await menuDelete(row.id)
          if (response.data.code === 200) {
            this.$message.success('删除成功')
            this.fetchMenuList() // 刷新列表
          } else {
            this.$message.error(response.data.message || '删除失败')
          }
        } catch (error) {
          console.error('删除菜单失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        // 用户取消删除
      })
    },
    submitDialogForm() {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          try {
            const params = {
              id: this.dialogForm.id,
              name: this.dialogForm.name,
              url: this.dialogForm.url,
              parentId: this.dialogForm.parentId === '0' ? 0 : parseInt(this.dialogForm.parentId),
              listorder: this.dialogForm.listorder
            }
            
            let response
            if (this.dialogForm.id) {
              // 编辑
              response = await menuEdit(params)
            } else {
              // 添加
              response = await menuAdd(params)
            }

            if (response.data.code === 200) {
              this.$message.success(this.dialogForm.id ? '编辑成功' : '添加成功')
              this.dialogVisible = false
              this.fetchMenuList() // 刷新列表
            } else {
              this.$message.error(response.data.message || (this.dialogForm.id ? '编辑失败' : '添加失败'))
            }
          } catch (error) {
            console.error(this.dialogForm.id ? '编辑菜单失败:' : '添加菜单失败:', error)
            this.$message.error(this.dialogForm.id ? '编辑失败' : '添加失败')
          }
        } else {
          // console.log('表单验证失败')
          return false
        }
      })
    },
    resetDialogForm() {
      this.$refs.dialogForm.resetFields()
      this.dialogForm = {
        id: null,
        name: '',
        url: '',
        parentId: '0',
        listorder: 0
      }
    },
    getColumnVisible(key) {
      const col = this.columns.find(c => c.key === key);
      return col ? col.visible : false;
    },
    resetColumns() {
      this.columns.forEach(col => col.visible = true);
    },
  }
}
</script>

<style scoped>
.menu-management-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px - 20px);
  box-sizing: border-box;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  align-items: center;
}

.filter-setting-icon {
  display: flex;
  align-items: center;
  height: 32px;
}

.table-wrapper {
  margin-top: 20px;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.pagination-info-total {
  margin-top: 20px;
  text-align: right;
  color: #606266;
  font-size: 14px;
}

/* 表格样式 */
::v-deep .el-table {
  border: 1px solid #EBEEF5;
}

::v-deep .el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
}

::v-deep .el-table td,
::v-deep .el-table th {
  border-bottom: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}

::v-deep .el-table th:last-child,
::v-deep .el-table td:last-child {
  border-right: none;
}

::v-deep .el-table::after,
::v-deep .el-table::before {
  background-color: transparent;
}

.dialog-footer {
  text-align: right;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 添加树形表格样式 */
::v-deep .el-table__expand-icon {
  margin-right: 8px;
}

::v-deep .el-table__expand-icon .el-icon {
  transition: transform 0.3s;
}

::v-deep .el-table__expand-icon--expanded .el-icon {
  transform: rotate(90deg);
}

::v-deep .el-table__row--level-1 {
  background-color: #fafafa;
}

::v-deep .el-table__row--level-2 {
  background-color: #f5f5f5;
}

::v-deep .el-table__row--level-3 {
  background-color: #f0f0f0;
}

::v-deep .el-input__inner {
  background-color: white !important;
}

@media (max-width: 768px) {
  .menu-management-container {
    padding: 15px 10px;
  }

  .filter-bar {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .filter-container {
    width: 100%;
    flex-wrap: wrap;
    gap: 10px;
  }

  .filter-container > * {
    margin-left: 0 !important;
  }

  .filter-container ::v-deep .el-date-editor,
  .filter-container ::v-deep .el-input,
  .filter-container ::v-deep .el-select,
  .filter-container ::v-deep .el-button {
    width: 100%;
  }

  .filter-setting-icon {
    align-self: flex-end;
  }

  .table-wrapper {
    margin-top: 10px;
  }

  ::v-deep .el-table {
    min-width: 700px;
    font-size: 12px;
  }

  ::v-deep .el-dialog {
    width: 90% !important;
  }
}
</style>